import { defineStore } from 'pinia'
import swal from 'sweetalert';
import type { FormInstance, FormRules } from 'element-plus'
import router from '@/router';
import request from '@/plugins/request';

export const useLoginStore = defineStore('LoginStore', () => {
    // 数据
    const ruleFormRef = ref<FormInstance>()
    const userLoginForm = reactive({
        username: '',
        password: ''
    })
    const reg_username: RegExp = /^[a-zA-Z0-9]{3,8}$/ // 数字或字母混合3-8位
    const reg_password: RegExp = /^[a-zA-Z0-9]{6,16}$/ // 数字或字母混合4-16位


    // 规则
    const rules = reactive<FormRules<typeof userLoginForm>>({
        username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
            { pattern: reg_username, message: '用户名格式不正确' }
        ],
        password: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { pattern: reg_password, message: '密码格式不正确' }
        ],
    })

    // 提交
    function submitForm(formEl: FormInstance | undefined) {
        if (!formEl) return
        formEl.validate(async (valid) => {
            if (valid) {
                // 处理数据，发送请求
                const { data: result } = await request.post('/userInfo/login', userLoginForm)
                if (result.code === 200) {
                    // 保存用户信息到localStore上
                    localStorage.setItem("userInfo", JSON.stringify(result.data))
                    swal("登录成功", "请求成功", "success");
                    router.push('/home')
                } else {
                    swal("登录失败", result.description || "系统错误", "error");
                }
            } else {
                swal("哒咩!", "你的登录信息不完整", "error");
            }
        })

    }

    function keyOn(){
        
    }


    return {
        ruleFormRef,
        userLoginForm,
        rules,
        submitForm,
        keyOn,
    }
})